import 'package:flutter/material.dart';
import 'package:flutter_changdian_football/api/api_response.dart';
import 'package:flutter_changdian_football/api/req/match/req_match.dart';
import 'package:flutter_changdian_football/api/req/other/req_other.dart';
import 'package:flutter_changdian_football/model/club/club_dynamic_model.dart';
import 'package:flutter_changdian_football/api/req/club/req_club.dart';
import 'package:flutter_changdian_football/config/enum/load_state.dart';
import 'package:flutter_changdian_football/model/club/club_center_model.dart';
import 'package:flutter_changdian_football/model/club/club_model.dart';
import 'package:flutter_changdian_football/routers/app_routes.dart';
import 'package:flutter_changdian_football/utils/custom_constant.dart';
import 'package:flutter_changdian_football/utils/event/custom_event_util.dart';
import 'package:flutter_changdian_football/utils/share_util.dart';
import 'package:flutter_changdian_football/widget/dialog/input_dialog.dart';
import 'package:flutter_changdian_football/widget/screenutil/custom_screenutil.dart';
import 'package:flutter_changdian_football/widget/sheet/share_icon_sheet.dart';
import 'package:flutter_changdian_football/widget/toast/custom_toast.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';

class ClubsController extends GetxController with GetTickerProviderStateMixin {

  List gnqList = [
    {
      'name': '俱乐部信息',
      'desc': 'Club information',
      'icon': 'assets/images/club_qy.png'
    },
    {
      'name': '财政',
      'desc': 'Finance',
      'icon': 'assets/images/club_cz.png'
    },
    {
      'name': '比赛记录',
      'desc': 'Create a Contest',
      'icon': 'assets/images/club_cjbs.png'
    },
    {
      'name': '球员',
      'desc': 'Football Player',
      'icon': 'assets/images/club_jlbxx.png'
    }
  ];

  TabController? tabController;

  ScrollController scrollController = ScrollController();
  // 范围 0-255
  int titleAlpha = 0;

  @override
  void onInit() {
    super.onInit();
    tabController = TabController(length: 2, vsync: this);
    scrollController.addListener(() {
      if (scrollController.offset > 150.w) {
        titleAlpha = 255;
      } else if (scrollController.offset <= 0) {
        titleAlpha = 0;
      } else {
        titleAlpha = scrollController.offset * 255 ~/ 150.w;
      }
      update();
    });

    initData();

    eventBus.on<BottomNavigationBarEvent>().listen((event) {
      if (event.message == CustomConstant.EVENT_REFRESH) {
        // 刷新数据
        initData();
      } else if (event.message == CustomConstant.EVENT_CLUB_REFRESH) {
        EasyLoading.show();
        initData();
      } else if (event.message == CustomConstant.EVENT_LOGOUT_REFRESH) {
        clearData();
      } else if (event.message == CustomConstant.EVENT_MATCH_REFRESH) {
        EasyLoading.show();
        initData();
      }
    });
  }

  clearData() {
    clublModel = null;
    clubList.clear();
    clubCenterModel = null;
    clubDynamicList.clear();
  }


  LoadState state = LoadState.loading;

  ClubModel? clublModel;
  List<ClubModel> clubList = [];

  initData() async {
    var resp = await ReqClub.getJoinClubList();
    if (resp.status == Status.completed) {
      if (resp.data['code'] == '200') {
        clubList.clear();
        for (int i = 0; i < resp.data['data'].length; i++) {
          clubList.add(ClubModel.fromJson(resp.data['data'][i]));
          if (resp.data['data'][i]['isDefault'].toString().toLowerCase() == "true".toLowerCase()) {
            clublModel = ClubModel.fromJson(resp.data['data'][i]);
          }
        }

        if (clubList.isNotEmpty) {
          // state = LoadState.success;
          clubCenter();
        } else {
          state = LoadState.empty;
        }
        update();
      } else {
        CustomToast.showTextToast('${resp.data['msg']}');
        state = LoadState.error;
        update();
      }
    } else {
      state = LoadState.network;
      update();
    }
  }

  /// 俱乐部主页
  ClubCenterModel? clubCenterModel;
  /// 动态
  List<ClubDynamicModel> clubDynamicList = [];

  /// 俱乐部主页
  clubCenter() async {
    try {
      await Future.wait<dynamic>([
        ReqClub.clubCenter(clubId: '${clublModel?.clubId ?? ''}'),
        ReqClub.clubDynamic(clubId: '${clublModel?.clubId ?? ''}', pageNum: '1', pageSize: '9999')
      ]).then((res){

        if (res[0].status == Status.completed) {
          if (res[0].data['code'] == '200') {
            clubCenterModel = ClubCenterModel.fromJson(res[0].data['data']);
          }
        }

        if (res[1].status == Status.completed) {
          if (res[1].data['code'] == '200') {
            for (int i = 0; i < res[1].data['data']['clubDynamicVOList'].length; i++) {
              clubDynamicList.add(ClubDynamicModel.fromJson(res[1].data['data']['clubDynamicVOList'][i]));
            }
          }
        }

        if (res[0].data['code'] == '200' && res[1].data['code'] == '200') {
          state = LoadState.success;
        }

        update();

      }).catchError((error){
        
      }); 
    } catch (e) {
      EasyLoading.dismiss();
    }
  }

  /// 显示名设置
  TextEditingController showNameSettingController = TextEditingController();

  displayName() async {
    try {
      EasyLoading.show();
      var resp = await ReqClub.displayName(
        clubId: '${clubCenterModel?.clubId}', 
      );
      if (resp.status == Status.completed) {
        if (resp.data['code'] == '200') {
          showNameSettingController.text = resp.data['data']['oldDisplayName'];
          InputDialog.show(
            Get.context!,
            title: "显示名设置",
            hintText: '请输入您的显示名',
            cancelTap: () {
              Get.back();
            },
            confirmTap: () {
              setPlayerClubDisplayName();
            },
            controller: showNameSettingController
          );
        } else {
          CustomToast.showTextToast(resp.data['msg'] ?? '系统异常，请稍后再试');
        }
      }
    } catch (e) {
      CustomToast.showTextToast('系统异常，请稍后再试');
    } finally {
      EasyLoading.dismiss();
    }
  }

  setPlayerClubDisplayName() async {
    FocusScope.of(Get.context!).requestFocus(FocusNode());
    if (showNameSettingController.text.trim() == '') {
      CustomToast.showTextToast('请输入您的显示名');
      return ;
    }
    try {
      EasyLoading.show();

      var resp = await ReqClub.setPlayerClubDisplayName(
        clubId: '${clubCenterModel?.clubId}',
        setName: showNameSettingController.text,
      );
      if (resp.status == Status.completed) {
        if (resp.data['code'] == '200') {
          CustomToast.showTextToast('操作成功');
          Get.back();
          eventBus.fire(const BottomNavigationBarEvent(CustomConstant.EVENT_CLUB_REFRESH));
        } else {
          CustomToast.showTextToast(resp.data['msg']);
        }
      } else {
        CustomToast.showTextToast('系统繁忙，请稍后再试！');
      }
    } catch (e) {
      CustomToast.showTextToast('系统繁忙，请稍后再试！');
    } finally {
      EasyLoading.dismiss();
    }
  }




  /// 分享
  getSharePage() async {
    try {
      EasyLoading.show();
      var resp = await ReqOther.getSharePage(sharePageName: CustomConstant.SHARE_CLUB_CENTER, clubId:'${ clubCenterModel?.clubId}');

      if (resp.data['code'] == '200') {
        // 分享推荐
        ShareIconSheet.shareIcon(
          null, 
          null, 
          resp.data['data']['url'], 
          null,
          isShowImg: false,
          wxTap: () {
            ShareUtil.shareUrl(title: resp.data['data']['sharePageName'], description: resp.data['data']['shareCardDescription'], image: resp.data['data']['shareCardImageUrl'],  url: resp.data['data']['shareUrl'], shareType: "0");
          },
          pyqTap: () {
            ShareUtil.shareUrl(title: resp.data['data']['sharePageName'], description: resp.data['data']['shareCardDescription'], image: resp.data['data']['shareCardImageUrl'],  url: resp.data['data']['shareUrl'], shareType: "1");
          },
          qqTap: () {
            ShareUtil.shareUrl(title: resp.data['data']['sharePageName'], description: resp.data['data']['shareCardDescription'], image: resp.data['data']['shareCardImageUrl'],  url: resp.data['data']['shareUrl'], shareType: "2");
          },
          wbTap: () {
            ShareUtil.shareUrl(title: resp.data['data']['sharePageName'], description: resp.data['data']['shareCardDescription'], image: resp.data['data']['shareCardImageUrl'],  url: resp.data['data']['shareUrl'], shareType: "3");
          },
        );
      } else {
        CustomToast.showTextToast(resp.data['msg']);
      }
    } catch (e) {
      CustomToast.showTextToast('系统繁忙，请稍后再试！');
    } finally {
      EasyLoading.dismiss();
    }
  }



  /// 比赛报名
  signUp(matchId) async {
    try {
      EasyLoading.show();

      var resp = await ReqMatch.signUp(
        matchId: '$matchId'
      );
      if (resp.status == Status.completed) {
        if (resp.data['code'] == '200') {
          CustomToast.showTextToast('操作成功');
          Get.back();
          eventBus.fire(const BottomNavigationBarEvent(CustomConstant.EVENT_MATCH_REFRESH));
        } else {
          CustomToast.showTextToast(resp.data['msg']);
        }
      } else {
        CustomToast.showTextToast('系统繁忙，请稍后再试！');
      }
    } catch (e) {
      CustomToast.showTextToast('系统繁忙，请稍后再试！');
    } finally {
      EasyLoading.dismiss();
    }
  }

  /// 取消报名
  cancelSignUp(matchId) async {
    try {
      EasyLoading.show();

      var resp = await ReqMatch.cancelSignUp(
        matchId: '$matchId'
      );
      if (resp.status == Status.completed) {
        if (resp.data['code'] == '200') {
          CustomToast.showTextToast('操作成功');
          eventBus.fire(const BottomNavigationBarEvent(CustomConstant.EVENT_MATCH_REFRESH));
        } else {
          CustomToast.showTextToast(resp.data['msg']);
        }
      } else {
        CustomToast.showTextToast('系统繁忙，请稍后再试！');
      }
    } catch (e) {
      CustomToast.showTextToast('系统繁忙，请稍后再试！');
    } finally {
      EasyLoading.dismiss();
    }
  }

  /// 切换俱乐部
  toggleDefaultClub(p) async {
    try {
      EasyLoading.show();

      var resp = await ReqClub.toggleDefaultClub(
        clubId: '$p'
      );
      if (resp.status == Status.completed) {
        if (resp.data['code'] == '200') {
          
          eventBus.fire(const BottomNavigationBarEvent(CustomConstant.EVENT_CLUB_REFRESH));
        } else {
          CustomToast.showTextToast(resp.data['msg']);
        }
      } else {
        CustomToast.showTextToast('系统繁忙，请稍后再试！');
      }
    } catch (e) {
      CustomToast.showTextToast('系统繁忙，请稍后再试！');
    } finally {
      EasyLoading.dismiss();
    }
  }

}